<script src="{{ static('libs/featherlight/featherlight.min.js') }}" type="text/javascript"></script>
{% compress js %}
    {{ comment_form.media.js }}
    <script type="text/javascript">
        $(document).ready(function () {
            window.reply_comment = function (parent) {
                var $comment_reply = $('#comment-' + parent + '-reply');
                var reply_id = 'reply-' + parent;
                var new_id = 'id' + parent + '_body';
                if ($comment_reply.find('#' + reply_id).length == 0) {
                    var $reply_form = $('#new-comment').clone(true).prop('id', reply_id);
                    $reply_form.find('h3').html('{{ _('Replying to comment') }}');
                    $reply_form.prepend('<a class="close">x</a>');
                    $reply_form.find('form.comment-submit-form input#id_parent').val(parent);
                    $reply_form.find('div#id_body-wmd-wrapper').prop('id', new_id + '-wmd-wrapper');
                    $reply_form.find('div#id_body_wmd_button_bar').empty().prop('id', new_id + '_wmd_button_bar');
                    $reply_form.find('textarea.wmd-input').val('').prop('id', new_id);
                    $reply_form.find('div#id_body-preview').attr('data-textarea-id', new_id).prop('id', new_id + '-preview');
                    $reply_form.appendTo($comment_reply);
                    register_dmmd_preview($reply_form.find('div#' + new_id + '-preview'));
                    if ('DjangoPagedown' in window) {
                        window.DjangoPagedown.createEditor($reply_form.find('textarea.wmd-input').get(0));
                    }
                }
                $comment_reply.fadeIn();

                $('html, body').animate({
                    scrollTop: $comment_reply.offset().top - $('#navigation').height() - 4
                }, 500);
            };

            $(document).on('click', '.close', function() {
                $(this).closest('.reply-comment').fadeOut();
            });

            function update_math($comment) {
                if ('MathJax' in window) {
                    var $body = $comment.find('.comment-body');
                    MathJax.typesetPromise([$body[0]]).then(function () {
                        $body.find('.tex-image').hide();
                        $body.find('.tex-text').show();
                    });
                }
            }

            window.show_revision = function (comment_id, offset) {
                var $comment = $("#comment-" + comment_id);

                // If .comment-body is hidden, then this is a bad comment that the user has not clicked
                // Thus the revision retrieval should do nothing
                if (!$comment.find('.comment-body').is(':visible'))
                    return;

                var cur_revision = parseInt($comment.attr("data-revision"));
                var max_revision = parseInt($comment.attr("data-max-revision"));
                var revision_ajax = $comment.attr("data-revision-ajax");
                var show_revision = cur_revision + offset;

                // Do nothing if desired revision is out of bounds
                if (show_revision < 0 || show_revision > max_revision)
                    return;

                $comment.attr("data-revision", show_revision);

                $.get(revision_ajax, {
                    revision: show_revision
                }).done(function (body) {
                    $comment.find('.previous-revision').css({visibility: show_revision == 0 ? 'hidden' : ''});
                    $comment.find('.next-revision').css({visibility: show_revision == max_revision ? 'hidden' : ''});
                    var $content = $comment.find('.content').html(body);

                    var edit_text = '{{ _('edit {edits}') }}'.replace("{edits}", show_revision);

                    if (show_revision == 0) {
                        edit_text = '{{ _('original') }}';
                    } else if (show_revision == max_revision && max_revision == 1) {
                        edit_text = '{{ _('edited') }}';
                    }

                    $comment.find('.comment-edit-text').text(' ' + edit_text + ' ');
                    update_math($content);
                    if (window.add_code_copy_buttons)
                        window.add_code_copy_buttons($content);
                });
            };

            function ajax_vote(url, id, delta, on_success) {
                return $.ajax({
                    url: url,
                    type: 'POST',
                    data: {
                        id: id
                    },
                    success: function (data, textStatus, jqXHR) {
                        var score = $('#comment-' + id + ' .comment-score').first();
                        score.text(parseInt(score.text()) + delta);
                        if (typeof on_success !== 'undefined')
                            on_success();
                    },
                    error: function (data, textStatus, jqXHR) {
                        alert('{{ _('Could not vote: {error}') }}'.replace('{error}', data.responseText));
                    }
                });
            }

            var get_$votes = function (id) {
                var $comment = $('#comment-' + id);
                return {
                    upvote: $comment.find('.upvote-link').first(),
                    downvote: $comment.find('.downvote-link').first()
                };
            };

            window.comment_upvote = function (id) {
                ajax_vote('{{ url('comment_upvote') }}', id, 1, function () {
                    var $votes = get_$votes(id);
                    if ($votes.downvote.hasClass('voted'))
                        $votes.downvote.removeClass('voted');
                    else
                        $votes.upvote.addClass('voted');
                });
            };

            window.comment_downvote = function (id) {
                ajax_vote('{{ url('comment_downvote') }}', id, -1, function () {
                    var $votes = get_$votes(id);
                    if ($votes.upvote.hasClass('voted'))
                        $votes.upvote.removeClass('voted');
                    else
                        $votes.downvote.addClass('voted');
                });
            };

            var $comments = $('.comments');
            $comments.find('a.hide-comment').click(function (e) {
                e.preventDefault();
                if (!(e.ctrlKey || e.metaKey || confirm('{{ _('Are you sure you want to hide this comment?') }}')))
                    return;

                var id = $(this).attr('data-id');
                $.post('{{ url('comment_hide') }}', {id: id}).then(function () {
                    $('#comment-' + id).remove();
                    $('#comment-' + id + '-children').remove();
                }).catch(function () {
                    alert('{{ _('Could not hide comment.') }}');
                });
            });

            $comments.find('a.edit-link').featherlight({
                afterOpen: function () {
                    if ('DjangoPagedown' in window) {
                        var $wmd = $('.featherlight .wmd-input');
                        if ($wmd.length) {
                            window.DjangoPagedown.createEditor($wmd.get(0));
                            if ('MathJax' in window) {
                                var preview = $('.featherlight div.wmd-preview')[0];
                                window.editors[$wmd.attr('id')].hooks.chain('onPreviewRefresh', function () {
                                    MathJax.typesetPromise([preview]);
                                });
                                MathJax.typesetPromise([preview]);
                            }
                        }
                    }
                    $('#comment-edit').submit(function (event) {
                        event.preventDefault();
                        var id = $('#comment-edit').find('.comment-id').text();
                        var readback = $('#comment-edit').find('.read-back').text();
                        $.post($(this).attr('action'), $(this).serialize()).done(function (data) {
                            $.featherlight.current().close();
                            $.ajax({
                                url: readback
                            }).done(function (data) {
                                var $comment = $('#comment-' + id);
                                var $area = $comment.find('.comment-body').first();
                                $area.html(data);
                                update_math($comment);
                                if (window.add_code_copy_buttons)
                                    window.add_code_copy_buttons($area);
                                var $edits = $comment.find('.comment-edits').first();
                                $edits.text('{{ _('updated') }}');
                            }).fail(function () {
                                alert('{{ _('Failed to update comment body.') }}');
                            });
                        }).fail(function (data) {
                            alert('{{ _('Could not edit comment: {error}') }}'.replace('{error}', data.responseText));
                        });
                    });
                },
                beforeClose: function () {
                    if ('DjangoPagedown' in window) {
                        var $wmd = $('.featherlight .wmd-input');
                        if ($wmd.length) {
                            window.DjangoPagedown.destroyEditor($wmd.get(0));
                        }
                    }
                },
                variant: 'featherlight-edit'
            });

            $('votes-link').find('a[data-featherlight]').featherlight();

            var $root = $('html, body');
            $comments.find('a.comment-link').click(function () {
                var href = $.attr(this, 'href');
                $root.animate({
                    scrollTop: $(href).offset().top
                }, 500, function () {
                    window.location.hash = href;
                });
                return false;
            });

            $('img.unveil').unveil(200);

            window.comment_show_content = function (comment_id) {
                var $comment = $('#comment-' + comment_id);
                $comment.find('.comment-body').show();
                $comment.find('.bad-comment-body').hide();
            };
        });
    </script>
{% endcompress %}
